package entity

import (
	"errors"
	"fmt"
	"time"

	"shqsoft.cn/pas3ui/workflow"
	"shqsoft.cn/pas3ui/workflow/entity"

	"gorm.io/gorm"
	"shqsoft.cn/pas3ui/base"
)

//SpYglz 员工离职
type SpYglz struct {
	ID       int       `gorm:"AUTO_INCREMENT;primary_key;column:ID" json:"id"`
	SQSJ     time.Time `gorm:"column:SQSJ" json:"sqsj"`
	EMNO     string    `gorm:"column:EMNO" json:"emno"`
	EMID     int       `gorm:"column:EMID" json:"emid"`
	EMNM     string    `gorm:"column:EMNM" json:"emnm"`
	FRID     int       `gorm:"column:FRID" json:"frid"`
	DPID     int       `gorm:"column:DPID" json:"dpid"`
	DPNM     string    `gorm:"column:DPNM" json:"dpnm"`
	YJBD_DG  int       `gorm:"column:YJBD_DG" json:"yjbd_dg"`
	YJBD_CX  int       `gorm:"column:YJBD_CX" json:"yjbd_cx"`
	YJBD_GD  int       `gorm:"column:YJBD_GD" json:"yjbd_gd"`
	UID      int       `gorm:"column:UID"`
	Progress float32   `gorm:"-" json:"progress"`
	StepName string    `gorm:"-" json:"stepName"`
	Status   string    `gorm:"-" json:"status"`
	STEP     int       `gorm:"-" json:"step"`
}

//TableName 员工离职表名
func (SpYglz) TableName() string {
	return "T_SP_YGLZ"
}

//BeforeSave 保存前的触发器
func (i *SpYglz) BeforeSave(tx *gorm.DB) (err error) {
	var user User
	err = tx.First(&user, i.EMID).Error
	if err != nil {
		return err
	}
	i.EMNO = user.No
	i.EMNM = user.Name
	var org Organization
	err = tx.First(&org, user.OrganizationID).Error
	if err != nil {
		return err
	}
	i.DPID = org.ID
	i.DPNM = org.Name
	var dsdt *time.Time
	dsdt, err = base.GetBackDATE()
	if err != nil {
		return err
	}
	if i.SQSJ.Unix() < dsdt.Unix() {
		return fmt.Errorf("离职员工%s的业绩变更追溯日期不能小于%s！", i.EMNM, dsdt.Format("20060102"))
	}
	if i.ID == 0 {
		var count int
		var frids []int
		err = tx.Table("T_SP_YGLZ").Where(`"EMID"=?`, i.EMID).Pluck(`"FRID"`, &frids).Error
		if err != nil {
			return err
		}
		row := tx.Raw(`select count("ID") from "T_FLOW_RUN" where "ID" in (?) and "STATE"='0'`, frids).Row()
		err = row.Scan(&count)
		if err != nil {
			return err
		}
		if count > 0 {
			return fmt.Errorf("用户:%s的离职申请已经在审批中，请不要重复申请！", user.Name)
		}
	}
	if i.ID > 0 {
		row := base.MYDB.Model(SpYglz{}).Where("ID=?", i.ID).Select("FRID").Row()
		row.Scan(&i.FRID)
	}
	if i.FRID == 0 {
		ei, _ := workflow.GetEntityInfo("SpYglz")
		var wfid int
		wfid, err = ei.WfidFunc(i)
		if err != nil {
			return err
		}
		if wfid == 0 {
			return errors.New("获取新公司账户申请WFID失败")
		}
		runid, err := workflow.Create(wfid, i.UID, tx)
		if err != nil {
			return err
		}
		i.FRID = runid
	}
	if i.YJBD_DG == 3 {
		err = createFs3List(i.FRID, 1, i.EMID)
		if err != nil {
			return err
		}
	}
	if i.YJBD_CX == 3 {
		err = createFs3List(i.FRID, 2, i.EMID)
		if err != nil {
			return err
		}
	}
	if i.YJBD_GD == 3 {
		err = createFs3List(i.FRID, 3, i.EMID)
		if err != nil {
			return err
		}
	}
	return
}

func (i *SpYglz) AfterDelete(tx *gorm.DB) (err error) {
	if i.FRID > 0 {
		return workflow.Delete(i.FRID)
	}
	return nil
}

// AfterFind 查询后触发器
func (i *SpYglz) AfterFind(tx *gorm.DB) (err error) {
	if i.FRID == 0 {
		i.Status = "exception"
		i.StepName = "校验错误"
		return
	}
	run := entity.FlowRun{}
	if err = tx.Find(&run, i.FRID).Error; err != nil {
		tx.Rollback()
		return
	}
	wf := workflow.GetWorkFlow(run.WFID)
	if wf == nil {
		return fmt.Errorf("指定的流程ID:%d在流程配置中不存在！", run.WFID)
	}
	act := wf.GetAction(run.Step)
	if act == nil {
		return fmt.Errorf("指定的stepID:%d在流程%s配置中不存在！", run.Step, wf.Name)
	}
	count := len(wf.Actions)
	i.STEP = run.Step
	i.StepName = act.Desc
	i.Progress = float32(act.Step*100) / float32(count)
	if i.Progress >= 100 && run.State == "0" {
		i.Progress = 95
	}
	i.Status = ""
	if run.State == "0" {
		i.Status = "active"
	} else if run.State == "2" {
		i.Status = "exception"
	} else {
		i.Status = "success"
	}
	return
}

func SpYglzEF() base.EntityFunc {
	return func() interface{} {
		entity := SpYglz{}
		return &entity
	}
}
func SpYglzESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []SpYglz
		return &entities
	}
}

func init() {
	ei, err := workflow.GetEntityInfo("SpYglz")
	if err != nil {
		panic(err)
	}
	dao := base.NewDefaultDao(SpYglzEF(), SpYglzESF(), nil, "my")
	filter := base.WorkFolowFilter{
		FilterColName: "FRID",
	}
	filter.SetAdditional("wfid", ei.WfidsToString())
	filter.SetAdditional("manager", ei.MgMapToString())
	dao.Fileter = &filter
	dao.Fileter.SetDB("my")
	base.DaoPoolObj.Put("SpYglz", dao)
}

func YglzFsChange(frid int, ywlx int, yjbd int) (err error) {
	var yglz SpYglz
	err = base.MYDB.First(&yglz, fmt.Sprintf(`"FRID"=%d`, frid)).Error
	if err != nil {
		return
	}
	if ywlx == 1 {
		yglz.YJBD_DG = yjbd
	} else if ywlx == 2 {
		yglz.YJBD_CX = yjbd
	} else if ywlx == 3 {
		yglz.YJBD_GD = yjbd
	} else {
		err = fmt.Errorf("无效的ywlx参数, ywlx必须1对公,2储蓄,3个贷")
		return
	}
	if yjbd == 3 {
		err = createFs3List(frid, ywlx, yglz.EMID)
		if err != nil {
			return
		}
	}
	err = base.MYDB.Save(&yglz).Error
	return
}
